package com.techedge.insidetrack

import org.springframework.dao.DataIntegrityViolationException

class UserController {

	static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

	/* ***************
	 * AVATAR ACTIONS
	 * ***************/
	def upload_avatar = {
		def user = User.current(session)  // or however you select the current user
		// Get the avatar file from the multi-part request
		def f = request.getFile('avatar')

		// List of OK mime-types
		def okcontents = ['image/png', 'image/jpeg', 'image/gif']
		if (! okcontents.contains(f.getContentType())) {
			flash.message = "Avatar must be one of: ${okcontents}"
			render(view:'select_avatar', model:[user:user])
			return;
		}

		// Save the image and mime type
		user.avatar = f.getBytes()
		user.avatarType = f.getContentType()
		log.info("File uploaded: " + user.avatarType)

		// Validation works, will check if the image is too big
		if (!user.save()) {
			render(view:'select_avatar', model:[user:user])
			return;
		}
		flash.message = "Avatar (${user.avatarType}, ${user.avatar.size()} bytes) uploaded."
		redirect(action:'show')
	}

	def avatar_image = {
		def avatarUser = User.get(params.id)
		if (!avatarUser || !avatarUser.avatar) {
			response.sendError(404)
			//OutputStream out = response.getOutputStream();
			//out.write(avatarUser.avatar);
			//out.close();
			return
		}
		response.setContentType(avatarUser.avatarType)
		response.setContentLength(avatarUser.avatar.size())
		OutputStream out = response.getOutputStream();
		out.write(avatarUser.avatar);
		out.close();
	}
	
	/* ***************
	 * LOGIN ACTIONS 
	 * ***************/
	def login() {
	}

	def logout() {
		session.login = null
		session.user = null
		redirect(uri: "/")
	}

	def doLogin() {
		def user = User.findWhere(	name:params.name,
				password:params.password)
		session.user = user
		session.login = true

		if (user){
			redirect(controller: params.controller, action: 'list')
		} else {
			redirect(controller:'user',action:'login')
		}
	}

	/* ***************
	 * STANDARD ACTIONS
	 * ***************/

	def index() {
		redirect(action: "list", params: params)
	}

	def list() {
		params.max = Math.min(params.max ? params.int('max') : 10, 100)
		[userInstanceList: User.list(params), userInstanceTotal: User.count()]
	}

	def create() {
		[userInstance: new User(params)]
	}

	def save() {
		def userInstance = new User(params)
		if (!userInstance.save(flush: true)) {
			render(view: "create", model: [userInstance: userInstance])
			return
		}

		flash.message = message(code: 'default.created.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
		redirect(action: "show", id: userInstance.id)
	}

	def show() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
			return
		}

		[userInstance: userInstance]
	}

	def edit() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
			return
		}

		[userInstance: userInstance]
	}

	def update() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
			return
		}

		if (params.version) {
			def version = params.version.toLong()
			if (userInstance.version > version) {
				userInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
						[message(code: 'user.label', default: 'User')] as Object[],
						"Another user has updated this User while you were editing")
				render(view: "edit", model: [userInstance: userInstance])
				return
			}
		}

		userInstance.properties = params

		if (!userInstance.save(flush: true)) {
			render(view: "edit", model: [userInstance: userInstance])
			return
		}

		flash.message = message(code: 'default.updated.message', args: [message(code: 'user.label', default: 'User'), userInstance.id])
		redirect(action: "show", id: userInstance.id)
	}

	def delete() {
		def userInstance = User.get(params.id)
		if (!userInstance) {
			flash.message = message(code: 'default.not.found.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
			return
		}

		try {
			userInstance.delete(flush: true)
			flash.message = message(code: 'default.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "list")
		}
		catch (DataIntegrityViolationException e) {
			flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'user.label', default: 'User'), params.id])
			redirect(action: "show", id: params.id)
		}
	}
}

